package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangyao.common.ApiResult;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.DateUtil;
import com.jiangyao.common.utils.FtpClient;
import com.jiangyao.common.utils.FtpClient;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.dao.*;
import com.jiangyao.model.dto.CollectDto;
import com.jiangyao.model.dto.DeliverDTO;
import com.jiangyao.model.dto.EditDeliverDTO;
import com.jiangyao.model.dto.JobDTO;
import com.jiangyao.model.dto.backend.AddJobDTO;
import com.jiangyao.model.dto.backend.EditJobAuditStatusDto;
import com.jiangyao.model.dto.backend.EditJobStatusDto;
import com.jiangyao.model.dto.backend.JobListDTO;
import com.jiangyao.model.entity.*;
import com.jiangyao.model.vo.CollectVo;
import com.jiangyao.model.vo.JobVo;
import com.jiangyao.model.vo.SendResumeVo;
import com.jiangyao.model.vo.UserSessionVO;
import com.jiangyao.service.JobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.bytebuddy.implementation.bytecode.Throw;
import org.dozer.DozerBeanMapper;
import org.dozer.MappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 职位 服务实现类
 * </p>
 *
 * @author zhoushuangxiang
 * @since 2020-08-12
 */
@Service
public class JobServiceImpl extends BaseServiceImpl<IJobDao, Job> implements JobService {

    @Autowired
    private IJobDao jobDao;

    @Autowired
    private ICategoryDao categoryDao;

    @Autowired
    private ICollectDao collectDao;

    @Autowired
    private IOrgInfoDao orgInfoDao;

    @Autowired
    private IResumeSendDao iResumeSendDao;

    @Autowired
    private DozerBeanMapper dozerBeanMapper;

    @Autowired
    private IJobDataDao iJobDataDao;

    @Override
    public PageInfo<JobVo> getWebJobList(JobDTO jobDTO) {
        PageHelper.startPage(jobDTO.getPageNo(),jobDTO.getPageSize());
        List<JobVo> jobList = jobDao.getWebJob(jobDTO);
        if(jobList.size() == 0){
            //throw new ServerException(500,"暂无数据");
            return new PageInfo(jobList);
        }
        setCollectLikeForList(jobList);
        PageInfo<JobVo> pageInfo = new PageInfo(jobList);
        return pageInfo;
    }

    private void setCollectLikeForList(List<JobVo> jobList){

        Set<Integer> jobSet = jobList.stream().collect(Collectors.toMap(JobVo::getJobId, a -> a,(k1, k2)->k1)).keySet();
        List<Integer> jobIdList = new ArrayList<>(jobSet);

        CollectDto dto = new CollectDto(1,getLoginApiUserId(),null,jobIdList);
        List<CollectVo> collectVoList = collectDao.selectCollectLikeList(dto);
        Map<Integer, CollectVo> groupby = collectVoList.stream().collect(Collectors.toMap(CollectVo::getRelateId, a -> a,(k1,k2)->k1));


        for(JobVo vo:jobList){
            if(groupby.get(vo.getJobId())!=null) {
                vo.setCollectNum(groupby.get(vo.getJobId()).getCollectNum());
                vo.setLikeNum(groupby.get(vo.getJobId()).getLikeNum());
                vo.setCurrentCollect(groupby.get(vo.getJobId()).getCurrentCollect());
                vo.setCurrentLike(groupby.get(vo.getJobId()).getCurrentLike());
            }
        }
    }

    private void setCollectLikeForOne(JobVo vo){
        CollectDto dto = new CollectDto(1,getLoginApiUserId(),vo.getJobId(),null);
        List<CollectVo> collectVoList = collectDao.selectCollectLikeList(dto);
        if(collectVoList!=null && collectVoList.size()==1) {
            vo.setCollectNum(collectVoList.iterator().next().getCollectNum());
            vo.setLikeNum(collectVoList.iterator().next().getLikeNum());
            vo.setCurrentCollect(collectVoList.iterator().next().getCurrentCollect());
            vo.setCurrentLike(collectVoList.iterator().next().getCurrentLike());
        }
    }

    private void setOrgInfoForOne(JobVo vo){
        OrgInfo org = orgInfoDao.selectById(vo.getOrgId());
        if(org!=null){
            vo.setOrgName(org.getOrgName());
            vo.setOrgLogo(FtpClient.fullFtpUrl(org.getOrgLogo()));
            vo.setOrgMinSize(org.getMinSize());
            vo.setOrgMaxSize(org.getMaxSize());
        }
    }

    @Override
    public JobVo getJobDetail(Integer jobId) {
        if(jobId==null || jobId<0){
            throw new ServerException(303, "参数不正确-jobId");
        }
        Job job = jobDao.selectById(jobId);
        JobVo vo = dozerBeanMapper.map(job, JobVo.class);
        if(job.getCategoryId()!=null && job.getCategoryId()>0){
            Category category = categoryDao.selectById(job.getCategoryId());
            if(category!=null){
                vo.setCategoryName(category.getName());
            }
        }
        //判断改职位是否投递过
        QueryWrapper<ResumeSend> resumeSendQueryWrapper = new QueryWrapper<>();
        resumeSendQueryWrapper.eq("org_id",job.getOrgId()).eq("user_id",getApiLoginSession().getUserId())
                .eq("job_id",job.getJobId());
        ResumeSend resumeSend1 = iResumeSendDao.selectOne(resumeSendQueryWrapper);
        if(resumeSend1 !=null){
            vo.setDeliver(1);
        }

        setCollectLikeForOne(vo);
        setOrgInfoForOne(vo);
        return vo;
    }

    @Override
    public List<SendResumeVo> getResumeSuccess(DeliverDTO deliverDTO) throws ServerException{
        UserSessionVO apiLoginSession = getApiLoginSession();
        deliverDTO.setUserId(apiLoginSession.getUserId());
        List<SendResumeVo> resumeSuccess = jobDao.getResumeSuccess(deliverDTO);
        if(resumeSuccess.size()==0){
            throw new ServerException(500,"暂无数据");
        }
        for (SendResumeVo success : resumeSuccess) {
            success.setOrgLogo(FtpClient.fullFtpUrl(success.getOrgLogo()));
        }
        return resumeSuccess;
    }

    @Override
    public Job addJob(AddJobDTO addJobDTO) throws ServerException{
        try {
            Job job = dozerBeanMapper.map(addJobDTO, Job.class);
            Date date = new Date();
            String endTime=addJobDTO.getEndTimeType();
            switch (endTime){
                case "0":
                    job.setEndTime(DateUtil.addTime(date, 1, 10));
                    break;
                case "1":
                    job.setEndTime(DateUtil.addTime(date,3,5));
                    break;
                case "2":
                    job.setEndTime(DateUtil.addTime(date, 3, 15));
                    break;
                case "3":
                    job.setEndTime(DateUtil.addTime(date,3,30));
                    break;
            }
            job.setCreateTime(new Date()).setCreateAdminId(getAdminLoginSession().getAdminId())
                    .setStartTime(date).setStatus(1);
            jobDao.insert(job);
            JobData jobData = new JobData();
            jobData.setJobId(job.getJobId());
            iJobDataDao.insert(jobData);
            return job;
        } catch (MappingException e) {
            throw new ServerException(100,"发布职位失败");
        }
    }

    @Override
    public Job editJob(AddJobDTO addJobDTO) throws ServerException{
        try {
            Job job = dozerBeanMapper.map(addJobDTO, Job.class);
            jobDao.updateById(job);
            return job;
        } catch (MappingException e) {
            throw new ServerException(501,"修改职位失败");
        }
    }

    @Override
    public PageInfo<JobVo> getJobList(JobListDTO jobListDTO) {
        PageHelper.startPage(jobListDTO.getPageNo(),jobListDTO.getPageSize());
        List<JobVo> jobList = jobDao.getJobList(jobListDTO);
        PageInfo<JobVo> pageInfo = new PageInfo(jobList);
        return pageInfo;
    }

    @Override
    public Job getBkJobDetail(Integer jobId) {
        if(jobId==null || jobId<0){
            throw new ServerException(303, "参数不正确-jobId");
        }
        Job job = jobDao.selectById(jobId);
        return job;
    }

    @Override
    public void editJobStatus(EditJobStatusDto editJobStatusDto) {
        jobDao.editJobStatus(editJobStatusDto);
    }

    @Override
    public void editJobAuditStatus(EditJobAuditStatusDto dto) {
        jobDao.editJobAuditStatus(dto);
    }
}
